<template>
    <div class="photo-list">
        <div v-if="Pictures?.length === 0" class="no-picture">
            <span style="font-size: 0.1rem;">该收藏夹还没有图片</span>
            <addPhoto />
        </div>
        <Picture v-for="item in Pictures" :item="item"></Picture>
    </div>
</template>

<script setup lang="ts">
import addPhoto from "@/components/addBox/addPhoto.vue";
import Picture from "@/components/Home/Picture.vue"
import { onMounted, ref, getCurrentInstance, onUnmounted } from "vue";
import { get } from "@/tools/api/api";
import { debounce } from "@/hooks/tools"
import { useRoute, useRouter } from "vue-router";
import { usePhotoStore } from "@/store/photo";
//引入路由
const route = useRoute()
const router = useRouter();
// 引入仓库
const photoStore = usePhotoStore();
// 引入实例
const instance = getCurrentInstance();

onMounted(() => {
    // 获取数据
    favoriteId.value = route.params.id
    getPhotos();

    // 滚动监听事件
    photoStore.page = 1;
    window.addEventListener("scroll", scrollLoad)
})
// 页面销毁，取消滚动监听
onUnmounted(() => {
    window.removeEventListener("scroll", scrollLoad)
})

// 滚动加载图片
const scrollLoad = () => {
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    let clientHeight = document.documentElement.clientHeight;
    let scrollHeight = document.documentElement.scrollHeight;
    if (scrollTop + clientHeight >= scrollHeight - 10) {
        //滚动到底部
        getPhotos();
    }
}

// 更新数据
instance?.proxy?.$Bus.on("reload", () => {
    getPhotos()
})

// 获取小收藏夹的id
const favoriteId = ref<string | string[]>('')
// 图片数据
const Pictures = ref<string[]>([]);
// 根据url信息获取图片
const getPhotos = debounce(() => {
    get("getImg", {
        favorite: favoriteId.value,
        page: photoStore.page,
        limit: photoStore.limit,
    }).then((res: any) => {
        if (res.code === 100) {
            // 查询成功
            if (res.data) {
                if (res.data && res.page === 1) {
                    Pictures.value = res.data
                    photoStore.$patch((state) => {
                        state.page++;
                    })
                } else {
                    if (res.page == photoStore.page) {
                        Pictures.value.push.apply(Pictures.value, res.data)
                        photoStore.$patch((state) => {
                            state.page++;
                        })
                    }
                }
                // 没有更多图片
                if (res.data?.length < photoStore.limit) {
                    window.removeEventListener("scroll", scrollLoad);
                }
            }
        }
    })
})


</script>

<style lang="scss" scoped>
$header-height: 0.3rem;
$logo-width: 0.6rem;
$a-font-size: 0.08rem;

.photo-list {
    height: auto;
    text-align: center;
    width: 100%;
    margin: $logo-width * 0.2 auto; // 剧中
    columns: 5; // 默认列数
    column-gap: $logo-width * 0.1; // 列间距
    overflow: auto;
}
</style>
